package com.gxnu.edu.cn.ttxxt.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gxnu.edu.cn.ttxxt.entity.Favorites;
import com.gxnu.edu.cn.ttxxt.mapper.FavoriteRepository;
import com.gxnu.edu.cn.ttxxt.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteRepository favoriteRepository;

    @Override
    @Transactional
    public void addFavorite(Long userId, Long contactId, Integer contactType) {
        // 检查是否已存在该收藏
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("contact_id", contactId)
                .eq("contact_type", contactType);

        if (favoriteRepository.selectCount(queryWrapper) > 0) {
            throw new IllegalArgumentException("该联系人已在收藏列表中");
        }

        // 创建新的收藏
        Favorites favorites = new Favorites();
        favorites.setUserId(userId);
        favorites.setContactId(contactId);
        favorites.setContactType(contactType);
        favorites.setSortOrder(0); // 默认排序
        favorites.setCreateTime(new Date());

        favoriteRepository.insert(favorites);
    }

    @Override
    @Transactional
    public void removeFavorite(Long userId, Long contactId) {
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("contact_id", contactId);

        if (favoriteRepository.delete(queryWrapper) == 0) {
            throw new IllegalArgumentException("未找到该收藏记录");
        }
    }

    @Override
    @Transactional
    public void updateFavoriteOrder(Long userId, Long contactId, Integer sortOrder) {
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("contact_id", contactId);

        Favorites favorites = favoriteRepository.selectOne(queryWrapper);
        if (favorites == null) {
            throw new IllegalArgumentException("未找到该收藏记录");
        }

        favorites.setSortOrder(sortOrder);
        favoriteRepository.updateById(favorites);
    }

    @Override
    public List<Favorites> getUserFavorites(Long userId) {
        QueryWrapper<Favorites> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .orderByAsc("sort_order") // 按排序顺序升序
                .orderByDesc("create_time"); // 其次按创建时间降序

        return favoriteRepository.selectList(queryWrapper);
    }
}